extends Control


const PORT: int = 7890


@onready var highscore_label: Label = $CenterContainer/MainUIContainer/PanelContainer/MarginContainer/VBoxContainer/HighscoreLabel as Label
@onready var _ip_address_line_edit: LineEdit = $CenterContainer/MainUIContainer/PanelContainer/MarginContainer/VBoxContainer/VBoxContainer/IpAddressLineEdit as LineEdit

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	_ip_address_line_edit.visible = OS.get_name() != "Web"
	highscore_label.text = "Highscore:{0}".format([ HighscoreManager.highscore ])
	if multiplayer.has_multiplayer_peer():
		multiplayer.multiplayer_peer.close()


func _on_play_button_pressed() -> void:
	var ip_address: String = _ip_address_line_edit.text
	if ip_address.is_empty():
		host_game()
	else:
		connect_to_game(ip_address)
	get_tree().change_scene_to_file("res://screens/game/main.tscn")


func _on_exit_button_pressed() -> void:
	get_tree().quit()


func host_game() -> void:
	var peer: ENetMultiplayerPeer = ENetMultiplayerPeer.new()
	var error = peer.create_server(PORT)
	if error != OK:
		print("create host server failed. Error: " + error)
		return
	if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
		print("host connection status is disconnected.")
		return
	multiplayer.multiplayer_peer = peer


func connect_to_game(ip_address: String) -> void:
	var peer: ENetMultiplayerPeer = ENetMultiplayerPeer.new()
	var error = peer.create_client(ip_address, PORT)
	if error != OK:
		print("create client failed. Error: " + error)
		return
	if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
		print("client connection status is disconnected.")
		return
	multiplayer.multiplayer_peer = peer
	
